// 这个hook用于操作本地存储

import { useMemo } from "react";

type Imethods = {
    set:(value:any) => void;
    rm:() => void
}


// key 存储到本地存储的key
// value  存储到本地的值
//重载window类型
declare global {
    interface Window {
        [k: string]: any
    }
}
/**
 * @param storageType 存储类型
 */
type Istorage = (key:string,storageType?:string) => [string,Imethods]


const useStorage:Istorage = (key,storageType = 'localStorage') => {

    // 设置localStorage的初识状态
    // let [localVal,setLocalVal] = useState<string | null>(null)

    // 从本地获取本地的值
    let localVal = useMemo<string | null>(()=>{
        let valueRes :string | null
        try{
            valueRes = JSON.parse(window[storageType].getItem(key))
            return valueRes ? valueRes : null
        }catch(e:any) {
            console.log(e.toString())
            return null
        }
    },[key])
    

    // 存储到本地
    // let set =(value:any) => {
    //     try{
    //         window[storageType].setItem(key,JSON.stringify(value))
    //     }catch(e:any){
    //         console.log(e.toString())
    //     }
    // }
    
    // 从本地获取
    // let get = () => {
    //     let valueRes :string | null
    //     try{
    //         valueRes = JSON.parse(window[storageType].getItem(key))
    //         return valueRes
    //     }catch(e:any) {
    //         console.log(e.toString())
    //         return null
    //     }
        
    // }

    // 移除
    // let rm = () => {
    //     window[storageType].removeItem(key)
    //     return 123
    // }

    let methodObj:Imethods = {
        // 设定缓存
        set:(value:any) => {
            try{
                window[storageType].setItem(key,JSON.stringify(value))
            }catch(e:any){
                console.log(e.toString())
            }
        },
        // 移除缓存
        rm:() => {
            window[storageType].removeItem(key)
            return 123
        }
    } 
    return [localVal!,methodObj]
}

export default useStorage